package com.hctforgreen.greenservice;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.db.DBManager;
import com.hctforgreen.greenservice.encoding.RGBLuminanceSource;
import com.hctforgreen.greenservice.machineManager.impl.Bigunit;
import com.hctforgreen.greenservice.machineManager.impl.JY_HotWaterMachine;
import com.hctforgreen.greenservice.machineManager.impl.MutipleMachine;
import com.hctforgreen.greenservice.machineManager.impl.SY_HotWaterMachine;
import com.hctforgreen.greenservice.model.BaseListItemEntity;
import com.hctforgreen.greenservice.model.BigUnitPasswordStatusEntity;
import com.hctforgreen.greenservice.model.BootPasswordEntity;
import com.hctforgreen.greenservice.model.IndustryEntity;
import com.hctforgreen.greenservice.model.LocationEntity;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.model.MachineListEntity.MachineEntity;
import com.hctforgreen.greenservice.model.PwdEntity;
import com.hctforgreen.greenservice.model.RelevanceEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.SerieEntity;
import com.hctforgreen.greenservice.model.SubmitBigUnitInfoEntity;
import com.hctforgreen.greenservice.service.HctApplication;
import com.hctforgreen.greenservice.ui.adapter.BaseSpinnerAdapter;
import com.hctforgreen.greenservice.ui.adapter.IndustryListAdapter;
import com.hctforgreen.greenservice.ui.widget.MyCustomDialog;
import com.hctforgreen.greenservice.utils.ContantsUtil;
import com.hctforgreen.greenservice.utils.DecodeBitmapUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.ImageCropUtil;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.LocationServiceUtil;
import com.hctforgreen.greenservice.utils.LogUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.MachineCodeUtil;
import com.hctforgreen.greenservice.utils.StringUtil;
import com.hctforgreen.greenservice.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;


/**
 * 开机密码
 *
 * @author ld 20140401
 *         wuhs 20151224更改
 *         将特殊机型的相关组件与初始化代码整理独立类
 *         <p>
 *         390697 201611增加
 *         增加开机密码机型提示、风管机和热水机的条码逻辑判断
 */
public class StartPwdActivity extends ParentActivity {
    private final String TAG = "StartPwdActivity";
    private Bundle loginBundle;//记录登陆接口传回来的参数

    private MutipleMachine mutipleMachine;//多联机管理类
    private SY_HotWaterMachine sy_HotWaterMachine;//商用热水机管理类
    private JY_HotWaterMachine jy_HotWaterMachine;//家用热水机管理类
    private Bigunit bigunit;//大机组管理类

    private LocationServiceUtil locationServiceUtil;//高德百度定位工具类
    private LocationEntity locationEntity = new LocationEntity();

    private Button sub_btn, scan_btn, pic_btn;
    private Spinner province_spinner, city_spinner, district_spinner;
    private EditText code_edit, address_edit, project_edit, name_edit,
            phone_edit, note_edit;

    private ImageButton backBtn;
    private Button btn_right;
    private TextView text_newMessage;
    private FrameLayout lyt_msg;

    private PwdEntity latestPwd;// 最近添加的开机密码

    public static final int ZXING_DATA = 3024;
    public static final int RESULT_LOAD_IMAGE = 3023;
    private Activity context;
    private SQLiteDatabase locationdb;//省市区数据库（外部导入的数据库文件）
    private List<BaseListItemEntity> p_list = new ArrayList<>();
    private Bitmap bitmap;// 图库二维码图片
    /**
     * 机型--1:多联机 2:家用热水机 3：商用热水机 4：大机组0：其它
     */
    private int MachineType;// 1:多联机 2:家用热水机 3：商用热水机 4：大机组0：其它
    private IndustryEntity industryEntity;//行业：中文/英文

    /**
     * 大机组开机密码状态改变通知条数
     */
    private int bigUnitPwdStatusMsg = 0;
    /**
     * 判断是否需要定位
     */
    private boolean loc = false;
    /**
     * DBManager数据库管理
     */
    private DBManager mgr;
    private DbController dbController;

    private final int FLAG_MODIFY_FINISH = RESULT_LOAD_IMAGE + 2;

    /**
     * 登录标识，用于判断登录掌上通正式服务器的次数，超过1次则判断为正式服务器宕机
     */
    public int pingCount = 0;
    /**
     * false为正式服务器，true为云服务器
     */
    private boolean isCloudServer = false;

    /**
     * 是否勾选批量安装
     */
    private boolean isBatchInstallation = false;
    private CheckBox cb_batchInstallation;

    private SharedPreferences mySharedPreferences;
    private Editor myEditor;
    /**
     * 是否是派工跳转过掌上通
     */
    private boolean isDispatching = false;


    //机型提示add  机型id 20161118 390697
    private String machineId;
    //风管机和热水机增加条码逻辑判断使用的机型名称  20161209 390697
    private String machineName;
    //条码弹框提示创建弹框的builder 20161213 390697
    private AlertDialog.Builder builder;
    private boolean wrongBarcode;

    //用于标记是否是从派工跳转过来的 true是从派工跳转过来的
    public boolean isGREEDAQ;

    @Override
    protected void onResume() {
        super.onResume();
        initSkinLayout();
        startLocationService();
        dbController = new DbController(StartPwdActivity.this);
    }

    /**
     * 初始化定位服务（高德、百度）
     * 390694--添加注释解析：两个定位服务同时进行，如果有一个先定位到地址则停止另外一个定位
     */
    private void startLocationService() {
        locationServiceUtil.startLocationService(this);
    }

    /**
     * 定位工具类LocationServiceUtil类回调此方法
     */
    public void onActivityLocationService(LocationEntity entity) {
        Toast.makeText(this, "掌上通成功获取定位", Toast.LENGTH_SHORT).show();
        locationEntity = entity;
        /*//add 390697 在关联资料中获取了开机密码后存入数据库中会使用到
        HctConstants.locationEntity = entity;*/

        address_edit.setText(entity.getStreet());
        BaseSpinnerAdapter myAdapter = new BaseSpinnerAdapter(StartPwdActivity.this, p_list);
        province_spinner.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();
        for (int i = 0; i < p_list.size(); i++) {
            if (locationEntity.getProvince_loc() != null && locationEntity.getProvince_loc().contains(p_list.get(i).getName())) {
                province_spinner.setSelection(i, true);
                break;
            }
        }
    }

    /**
     * 派工系统调入登陆 wuhs 2015/10/8
     */
    private void doLoginin(final String phone, final String onlyCode,
                           final String imeiCode) {

        MobclickAgent.onEvent(this, "Account_login");
        /**
         * 2016 11 28 390778
         * 修改友盟jar
         *
         * 去除MobclickAgent.onEventBegin(this, "Account_login");
         * MobclickAgent.onEventEnd(LoginActivity.this, "Account_login");
         * 该方法废除
         * 统计登录时间，需要自己去获取经历的时间，然后将其传出
         */
        //获取当前时间的毫秒值
        final long firstTime = System.currentTimeMillis();

        @SuppressLint("HandlerLeak")
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {

                //登陆之后的毫秒值
                long secondTime = System.currentTimeMillis();
                int time = (int) (secondTime - firstTime);
//				使用该方法将时间传给友盟统计
                MobclickAgent.onEventValue(context, "Account_login", null, time);

                HctResult hctResult = new HctResult();

				/*2016.3.9号之前所注释的代码位置如下，2016.3.9修改为放置在case HctConstants.STATUS_SUCCESS里
                 * hctResult = (HctResult) msg.obj;
				LoginResultEntity entity = (LoginResultEntity) hctResult.data;
				entity.phone = phone;*/


                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:

                        //390694 2016.3.9改
                        hctResult = (HctResult) msg.obj;
                        LoginResultEntity entity = (LoginResultEntity) hctResult.data;
                        entity.phone = phone;

                        if (entity.loginStatus.equals("0")) {//正常登陆
                            if (getIntent().getExtras() != null) {
                                loginBundle = getIntent().getExtras();//记录登陆接口传回来的参数，在重新打开主界面时可以调用
                                //add 390697 用于保存是否从派工跳转过来的 机型提示中使用
                                if (loginBundle != null) {
                                    isGREEDAQ = true;
                                }

                            }
                            String fun = entity.functions;
                            if (entity.functions.contains("!1!")) {// 有开机密码权限
                                LoginResultStoreUtil.save(StartPwdActivity.this,
                                        entity);// 保存用户信息
                                return;
                            } else {// 无开机密码权限时，重新登陆
                                Toast.makeText(
                                        StartPwdActivity.this,
                                        phone
                                                + getString(R.string.auto_login_nogetpassword_warn),
                                        Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent();
                                intent.setClass(StartPwdActivity.this,
                                        LoginActivity.class);
                                intent.putExtra("phone", phone);
                                intent.putExtra("isDispatching", isDispatching);
                                startActivity(intent);
                                finish();
                            }

                        } else {
                            Toast.makeText(StartPwdActivity.this,
                                    getString(R.string.auto_login_warn),
                                    Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.setClass(StartPwdActivity.this,
                                    LoginActivity.class);
                            intent.putExtra("phone", phone);
                        /*390694--2016.5.26添加
                         *是否是派工跳转的值传给登录界面
						 */
                            intent.putExtra("isDispatching", isDispatching);
                            startActivity(intent);
                            finish();
                        }
                        break;

                    case HctConstants.STATUS_FAILD:
                        Toast.makeText(StartPwdActivity.this,
                                getString(R.string.auto_login_warn),
                                Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent();
                        intent.setClass(StartPwdActivity.this, LoginActivity.class);
                        intent.putExtra("phone", phone);
                    /*390694--2016.5.26添加
                     *是否是派工跳转的值传给登录界面
					 */
                        intent.putExtra("isDispatching", isDispatching);
                        startActivity(intent);
                        finish();
                        break;
                }
            }
        };

        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(
                            StartPwdActivity.this);
                    HctResult result = controller.appLogin(phone, onlyCode,
                            imeiCode, "", "", pingCount);

                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }

                } catch (Exception e) {
                    message.what = HctConstants.STATUS_FAILD;
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        context = this;
        super.onCreate(savedInstanceState);
        locationdb = ((HctApplication) getApplication()).getLocationdb();
        locationServiceUtil = ((HctApplication) getApplication()).getLocationServiceUtil();

        setContentView(R.layout.activity_start_pwd);
        initClickEdgehideKeyboard();

        loc = getIntent().getBooleanExtra("loc", false);
        pingCount = getIntent().getIntExtra("PING_COUNT", 0);
        isCloudServer = getIntent().getBooleanExtra("WHICH_SERVER", false);

        mySharedPreferences = this.getSharedPreferences(HctConstants.START_PW_SHAREPAREFRANCE_FILE_NAME, Context.MODE_WORLD_WRITEABLE);
        myEditor = mySharedPreferences.edit();

        // 从偏好设置获取是否批量安装
        isBatchInstallation = mySharedPreferences.getBoolean(HctConstants.KEY_VALUE_BATCH_INSTALLATION, false);

        //增加派工系统跳转到该activity
        MachineCodeUtil codeUtil = new MachineCodeUtil(context);
        String phone = getIntent().getStringExtra("phone");
        ContantsUtil.sPhoneNumber = phone;
        if (phone != null && getIntent().getStringExtra("barcode") != null) {
            loc = true;// 需要定位
            //2016.4.28--390694增加派工工程名判断
            isDispatching = true;
            doLoginin(phone, codeUtil.getMachineCode(), codeUtil.getIMEICode());
        }
        //初始化组件
        initWidget();
        //控件监听、
        setListener();
        mgr = new DBManager(context);
        //访问获取大机组的审核状态及正常密码的接口，并将获取到的数据存入数据库
        getBigUnitExamineStatus(LoginResultStoreUtil.get(context).phone, LoginResultStoreUtil.get(context).personId, isCloudServer);

        /**
         * 获取最近的一条开机密码
         */
        new HandlerThread("getLatestPwd") {
            public void run() {
                final List<PwdEntity> pwds = mgr.queryAll();
                runOnUiThread(new Runnable() {
                    public void run() {
                        if (pwds == null || pwds.isEmpty()) {
                            // 没有最近记录，则显示派工传来的值
                            Bundle bundle = getIntent().getExtras();
                            String barcode = bundle.getString("barcode");
                            String projectName = bundle
                                    .getString("projectName");
                            String owner = bundle.getString("owner");
                            String ownerPhone = bundle.getString("ownerPhone");


                            code_edit.setText(barcode != null ? barcode : "");
                            project_edit
                                    .setText(projectName != null ? projectName
                                            : "");
                            name_edit.setText(owner != null ? owner : "");
                            phone_edit.setText(ownerPhone != null ? ownerPhone
                                    : "");
                            return;
                        }
                        latestPwd = pwds.get(0);
                        /**
                         * 2016.5.12   390694添加
                         * 增加派工跳转判断
                         */
                        if (isDispatching) {
                            showLatestPwd(latestPwd);
                            return;
                        }

                        /**2016.5.1--390694添加
                         * 如果勾选批量安装，则工程名、用户信息、安装行业信息保留最近一次开机密码的值
                         */
                        if (isBatchInstallation) {
                            showLatestPwd(latestPwd);
                        } else {
                            code_edit.setText("");
                            project_edit.setText("");
                            name_edit.setText("");
                            phone_edit.setText("");
                            note_edit.setText("");
                            initIndustryBtn("");
                        }
                    }
                });
            }
        }.start();
    }


    /**
     * 安装行业
     */
    private void initIndustryBtn(final String industry) {
        final Spinner industryBtn = (Spinner) findViewById(R.id.btn_industry);
        final IndustryListAdapter listAdapter = new IndustryListAdapter(
                StartPwdActivity.this);
        industryBtn.setAdapter(listAdapter);

        //如果勾选批量安装，则安装行业信息保留最近一次开机密码的值
        if (isBatchInstallation) {
            ArrayList<IndustryEntity> myIndustryList = listAdapter
                    .getIndustryList();
            int select = 0;
            for (int index = 0; index < myIndustryList.size(); index++) {
                if ((myIndustryList.get(index).name).equals(industry)) {
                    select = index;
                }
            }
            industryBtn.setSelection(select, true);
        }

        industryBtn.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                ArrayList<IndustryEntity> IndustryList = listAdapter
                        .getIndustryList();
                industryBtn.setTag(IndustryList.get(position));


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    /**
     * 点击边缘隐藏输入法
     */
    private void initClickEdgehideKeyboard() {
        LinearLayout rootLyt = (LinearLayout) findViewById(R.id.lyt_root);
        rootLyt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                KeyboardUtil keyboardUtil = new KeyboardUtil();
                keyboardUtil.hideSoftKeyboard(v);
                code_edit.clearFocus();
            }
        });
    }

    // 显示最近一条开机密码
    private void showLatestPwd(PwdEntity pwdEntity) {
        //由派工传来的参数
        Bundle bundle = getIntent().getExtras();
        String phone = bundle.getString("phone");
        String barcode = bundle.getString("barcode");
        String projectName = bundle.getString("projectName");
        String owner = bundle.getString("owner");
        String ownerPhone = bundle.getString("ownerPhone");
        String industry = bundle.getString("installPlace");


        //如果历史记录为空、派工无传参数，则返回
        if (pwdEntity == null && phone == null) {
            return;
        }
        //2016.4.28--390694增加派工工程名判断
        if (isDispatching) {
            if (projectName != null) {
                project_edit.setText(projectName);
            } else {
                project_edit.setText("");
            }
        } else {
            project_edit.setText(pwdEntity.projectName);
        }
        code_edit.setText(barcode != null ? barcode : "");
        /*project_edit.setText(projectName != null ? projectName
                : pwdEntity.projectName);*/
        name_edit.setText(owner != null ? owner : pwdEntity.ownerName);
        phone_edit.setText(ownerPhone != null ? ownerPhone
                : pwdEntity.ownerPhone);
        note_edit.setText(pwdEntity.note);
        initIndustryBtn(industry != null ? industry : pwdEntity.industry);


    }

    private void initWidget() {

        mutipleMachine = new MutipleMachine(context);//初始化多联机相应的组件
        sy_HotWaterMachine = new SY_HotWaterMachine(context);//初始化商用热水机相应的组件
        jy_HotWaterMachine = new JY_HotWaterMachine(context);//初始化家用热水机相应的组件
        bigunit = new Bigunit(context);//初始化大机组相应的组件

        mutipleMachine.initView();
        sy_HotWaterMachine.initView();
        jy_HotWaterMachine.initView();
        bigunit.initView();

        final TextView titleTv = (TextView) findViewById(R.id.tv_title);
        titleTv.setText(getString(R.string.title_start_pwd));
        lyt_msg = (FrameLayout) findViewById(R.id.lyt_msg);
        text_newMessage = (TextView) lyt_msg
                .findViewById(R.id.tv_new_msg_count);
        backBtn = (ImageButton) findViewById(R.id.btn_back);
        backBtn.setOnClickListener(mOnClick);
        btn_right = (Button) findViewById(R.id.btn_right);
        btn_right.setOnClickListener(mOnClick);
        btn_right.setVisibility(View.VISIBLE);
        btn_right.setBackgroundResource(R.drawable.btn_pwd_history_selector);
        final Button btn_right_first = (Button) findViewById(R.id.btn_right_first);
        btn_right_first
                .setBackgroundResource(R.drawable.btn_common_help_selector);
        btn_right_first.setOnClickListener(mOnClick);

        sub_btn = (Button) findViewById(R.id.sub_btn);
        sub_btn.setOnClickListener(mOnClick);
        scan_btn = (Button) findViewById(R.id.scan_btn);
        scan_btn.setOnClickListener(mOnClick);
        pic_btn = (Button) findViewById(R.id.pic_btn);
        pic_btn.setOnClickListener(mOnClick);
        province_spinner = (Spinner) findViewById(R.id.province_spinner);
        city_spinner = (Spinner) findViewById(R.id.city_spinner);
        district_spinner = (Spinner) findViewById(R.id.district_spinner);
        code_edit = (EditText) findViewById(R.id.code_edit);
        address_edit = (EditText) findViewById(R.id.address_edit);
        project_edit = (EditText) findViewById(R.id.project_edit);
        name_edit = (EditText) findViewById(R.id.name_edit);
        phone_edit = (EditText) findViewById(R.id.phone_edit);
        note_edit = (EditText) findViewById(R.id.note_edit);

        cb_batchInstallation = (CheckBox) findViewById(R.id.cb_batch_installation);
        cb_batchInstallation.setChecked(mySharedPreferences.getBoolean(HctConstants.KEY_VALUE_BATCH_INSTALLATION, false));

        province_spinner.setPrompt("选择省份");
        city_spinner.setPrompt("选择城市");
        district_spinner.setPrompt("选择地区");

        initSpinner1();
        initIndustryBtn(null);

        //增加热水机和风管机的条码逻辑判断，避免用户扫错地方    390697 20161209
        code_edit.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {// 失去焦点是进行条码校验
                    //add 390697 在失去焦点时开始查询
                    getMachineIdFromDb(code_edit.getText().toString());
                    barcodeValidate();//在此处增加热水机和风管机的条码逻辑判断
                }
            }

        });
        code_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        code_edit.setFocusable(true);
    }


    /**
     * 获取开机密码
     **/
    private void getBootPwd(final PwdEntity paramEntity) {
        if (wrongBarcode) {
            //			builder.create().show();
        } else {//只有在条码正确的情况下
            final ProgressBar loadPb = (ProgressBar) findViewById(R.id.pb_loading);
            sub_btn.setClickable(false);
            loadPb.setVisibility(View.VISIBLE);
            MobclickAgent.onEvent(this, "Submit_start_pwd");
            @SuppressLint("HandlerLeak")
            final Handler handler = new Handler() {
                public void handleMessage(Message msg) {
                    sub_btn.setClickable(true);
                    loadPb.setVisibility(View.GONE);
                    ArrayList<PwdEntity> pwdlist = new ArrayList<PwdEntity>();
                    HctResult hctResult = new HctResult();
                    switch (msg.what) {
                        case HctConstants.STATUS_SUCCESS:
                            hctResult = (HctResult) msg.obj;
                            // 先判断是否是大机组提交数据
                            if (hctResult.isBigUnit) {// 大机组点击提交时获取开机密码处理动作
                                SubmitBigUnitInfoEntity mBigUnitPasswordEntity = (SubmitBigUnitInfoEntity) hctResult.data;

                                if (mBigUnitPasswordEntity.statusCode.equals("0")) {

                                    paramEntity.date = Utils.getNowDate();
                                    paramEntity.identityCode = bigunit.getDataForBigUnit().identityCode;
                                    paramEntity.isBigUnit = "1";
                                    paramEntity.time = Utils.getNowTimeHM();
                                    paramEntity.stripeCode = paramEntity.stripeCode.split(",")[0];
                                    paramEntity.sparebootPwd = "";
                                    paramEntity.finished = "0";

                                    paramEntity.industry = industryEntity.name;//保存本地时，行业存中文

                                    pwdlist.add(paramEntity);

                                    // 保存到本地数据库
                                    mgr.add(pwdlist);


                                } else if (!mBigUnitPasswordEntity.statusCode
                                        .equals("0")) {
                                    if (!mBigUnitPasswordEntity.unitMsg.equals("")) {
                                        Toast.makeText(context,
                                                mBigUnitPasswordEntity.unitMsg,
                                                Toast.LENGTH_SHORT).show();
                                    } else if (mBigUnitPasswordEntity.unitMsg
                                            .equals("")) {

                                        Toast.makeText(context,
                                                getString(R.string.net_error_hint),
                                                Toast.LENGTH_SHORT).show();
                                    }
                                    break;
                                }
                            } else {// 其他机型点击提交时获取开机密码处理。其他机型获取的开机密码
                                BootPasswordEntity mBootPasswordEntity = (BootPasswordEntity) hctResult.data;
                                if (mBootPasswordEntity.statusCode.equals("0")) {

								/*
                                 * 修改获取开机密码 wuhs 20150715
								 */
                                    String[] mas = paramEntity.stripeCode.split(",");// 条码
                                    String[] pds = mBootPasswordEntity.bootPwd.split(",");

                                    // 先保存本地数据库
                                    for (int i = 0; i < mas.length; i++) {
                                        PwdEntity entity = new PwdEntity();
                                        entity.phone = paramEntity.phone;
                                        entity.street = paramEntity.street;
                                        entity.projectName = paramEntity.projectName;
                                        entity.ownerName = paramEntity.ownerName;
                                        entity.ownerPhone = paramEntity.ownerPhone;
                                        entity.remark = paramEntity.remark;

                                        entity.stripeCode = mas[i];
                                        entity.industry = industryEntity.name;//保存本地时，行业存中文
                                        entity.province = locationEntity.getProvince();
                                        entity.city = locationEntity.getCity();
                                        entity.district = locationEntity.getDistrict();
                                        entity.date = Utils.getNowDate();
                                        entity.openPassword = pds[i]
                                                .replace("[", "").replace("]", "")
                                                .replace("\"", "");
                                        entity.time = Utils.getNowTimeHM();
                                        entity.stripeCode = mas[i];
                                        entity.sparebootPwd = "";
                                        pwdlist.add(entity);
                                    }
                                    // 保存到本地数据库
                                    mgr.add(pwdlist);
                                } else if (!mBootPasswordEntity.statusCode.equals("0")) {
                                    if (!mBootPasswordEntity.bootMsg.equals("")) {
                                        Toast.makeText(context, mBootPasswordEntity.bootMsg, Toast.LENGTH_SHORT).show();
                                    } else if (mBootPasswordEntity.bootMsg.equals("")) {
                                        Toast.makeText(context, getString(R.string.net_error_hint), Toast.LENGTH_SHORT).show();
                                    }
                                    break;
                                }

                            }
                            // 保存后跳转
                            Intent intent = new Intent();
                            intent.setClass(context, ShowPwdActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putParcelableArrayList("pwdlist", pwdlist);
                            if (loginBundle != null) {//派工标志位
                                bundle.putBoolean("isGREEDAQ", true);
                            }
                            intent.putExtras(bundle);
                            //传递服务器类型判断结果至开机密码列表界面
                            intent.putExtra("PING_COUNT", pingCount);
                            intent.putExtra("WHICH_SERVER", isCloudServer);
                            startActivity(intent);
                            break;
                        case HctConstants.STATUS_FAILD:
                            Toast.makeText(context, getString(R.string.net_error_hint), Toast.LENGTH_SHORT).show();
                            break;
                    }
                }
            };
            new Thread() {
                public void run() {
                    Message message = new Message();
                    try {
                        HctController controller = new HctController(context);
                        HctResult result = new HctResult();
                        switch (MachineType) {
                            case 0:
                                result = controller.getBootPwd(paramEntity.phone,
                                        paramEntity.stripeCode,
                                        locationEntity.getmGpsLocation(),
                                        locationEntity.getmBaseLocation(),
                                        locationEntity.getmWifiLocation(),
                                        locationEntity.getProvince_loc(),
                                        locationEntity.getCity_loc(),
                                        locationEntity.getProvince(),
                                        locationEntity.getCity(),
                                        locationEntity.getDistrict(),
                                        paramEntity.street, paramEntity.projectName,
                                        paramEntity.ownerName, paramEntity.ownerPhone,
                                        paramEntity.remark, paramEntity.industry, "",
                                        "", "", "", "", "", "", "", "", "",
                                        locationEntity.getmLatitude() + "",
                                        locationEntity.getmLongitude() + "", "", isCloudServer);
                                break;
                            case 1:
                                result = mutipleMachine.getPwdResult(paramEntity, locationEntity, isCloudServer);
                                break;
                            case 2:
                                result = jy_HotWaterMachine.getPwdResult(paramEntity, locationEntity, isCloudServer);
                                break;
                            case 3:
                                result = sy_HotWaterMachine.getPwdResult(paramEntity, locationEntity, isCloudServer);
                                break;
                            case 4:
                                result = bigunit.getPwdResult(paramEntity, locationEntity, isCloudServer);
                                break;
                        }

                        if (result.status == HctConstants.STATUS_SUCCESS) {
                            message.what = result.status;
                            message.obj = result;
                        } else {
                            message.what = HctConstants.STATUS_FAILD;
                        }
                    } catch (Exception e) {
                        message.what = HctConstants.STATUS_FAILD;
                        e.printStackTrace();
                    }
                    handler.sendMessage(message);
                }
            }.start();
        }
    }

    /**
     * 获取开机密码提醒信息和详细资料
     *
     * @param
     */
    private void showRelevanceHint(final String machineId, final PwdEntity pwd) {

        final ProgressBar loadPb = (ProgressBar) findViewById(R.id.pb_loading);
        sub_btn.setClickable(false);
        loadPb.setVisibility(View.VISIBLE);

        final Handler handler = new Handler() {
            public void dispatchMessage(Message msg) {
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        loadPb.setVisibility(View.GONE);
                        HctResult hctResult = (HctResult) msg.obj;
                        try {
                            final RelevanceEntity entity = (RelevanceEntity) hctResult.data;
                            if (entity == null) {
                                return;
                            }
                            int flag = entity.flag;
                            String content = "";
                            StringBuilder builder = new StringBuilder(content);
                            //flag 0 没有提示 1 只有提示内容 2 只有书或者视频 3 提示内容和书都有
                            if (flag == 0) {
                                getBootPwd(pwd);
                                return;
                            } else {
                                if (!TextUtils.isEmpty(entity.content)) {
                                    builder.append(entity.content + "\n");
                                }

                                if (flag != 1) {
                                    if (flag == 2 && (entity.bookList == null) && (entity.vedioList == null)) {
                                        //如果书或者视频都为空,不弹框，直接获取开机密码
                                        getBootPwd(pwd);
                                        return;
                                    }

                                    if ((entity.bookList != null) && (entity.bookList.size() > 0)) {
                                        for (int i = 0; i < entity.bookList.size(); i++) {
                                            RelevanceEntity.BookClass bookClass = entity.bookList.get(i);
                                            String bookName = bookClass.bookName;
                                            builder.append(i + 1 + "." + bookName + ";\n");
                                        }
                                    }

                                    if ((entity.vedioList != null) && (entity.vedioList.size() > 0)) {
                                        int oldLength = 0;
                                        if (entity.bookList != null && entity.bookList.size() > 0) {
                                            oldLength = entity.bookList.size();
                                        }

                                        for (int i = 0; i < entity.vedioList.size(); i++) {
                                            builder.append((oldLength + i + 1) + "." + entity.vedioList.get(i).vedioName + ";\n");
                                        }
                                    }
                                }
                            }

                            if (flag == 1) {
                                new MyCustomDialog().showSingleButtonAlert(StartPwdActivity.this, "", builder.toString(), "", new MyCustomDialog.OnAlertSelected() {
                                    @Override
                                    public void onClick(int whichButton) {
                                        getBootPwd(pwd);
                                    }
                                });
                            } else {
                                new MyCustomDialog().showAlert(StartPwdActivity.this, "", builder.toString(), "", "", new MyCustomDialog.OnAlertSelected() {
                                    @Override
                                    public void onClick(int whichButton) {
                                        if (whichButton == MyCustomDialog.YES) {
                                            //看 有资料 or 无资料
                                            Intent intent = new Intent();
                                            intent.putExtra("PwdEntity", pwd);
                                            switch (MachineType) {
                                                // 1:多联机 2:家用热水机 3：商用热水机 4：大机组0：其它
                                                case 1:
                                                    intent.putExtra("mutipleMachine", mutipleMachine.mutipleMachineEntity);
                                                    break;
                                                case 2:
                                                    intent.putExtra("jy_HotWaterMachine", jy_HotWaterMachine.jyHotWaterMachineEntity);
                                                    break;
                                                case 3:
                                                    if (sy_HotWaterMachine.engineeringType == 1) {
                                                        intent.putExtra("sy_HotWaterMachine", sy_HotWaterMachine.comHotWater.syHotWaterMachineEntity);
                                                    } else {
                                                        intent.putExtra("sy_HotWaterMachine", sy_HotWaterMachine.comFloorHeat.syHotWaterMachineEntity);
                                                    }
                                                    break;
                                                case 4:
                                                    intent.putExtra("bigunit", bigunit.dataForBigUnit);
                                                    break;
                                                case 0:
                                                    break;
                                                default:
                                                    break;
                                            }

                                            intent.putExtra("bookList", entity.bookList);
                                            intent.putExtra("vedioList", entity.vedioList);
                                            intent.putExtra("MachineType", MachineType);
                                            intent.putExtra("PING_COUNT", pingCount);
                                            intent.putExtra("WHICH_SERVER", isCloudServer);
                                            intent.putExtra("locationEntity", locationEntity);
                                            intent.putExtra("industryEntity", industryEntity);
                                            intent.putExtra("isGREEDAQ", isGREEDAQ);
                                            intent.setClass(StartPwdActivity.this, MachineRelevanceTipActivity.class);
                                            startActivity(intent);
                                            //获取一次关联提示后返回当前页面，提交按钮恢复可点击
                                            sub_btn.setClickable(true);
                                        } else {
                                            //不看 给开机密码
                                            getBootPwd(pwd);
                                        }
                                    }
                                });
                            }
                        } catch (Exception ec) {
                            ec.printStackTrace();
                        }
                        break;
                    case HctConstants.STATUS_FAILD:
                        LogUtil.i("DATA", "关联提示异常");
                        //2017-2-13 若接口出现异常，则直接获取开机密码
                        getBootPwd(pwd);
                        break;
                }
            }

            ;
        };

        new HandlerThread("getRelevance") {
            public void run() {
                HctController controller = new HctController(
                        StartPwdActivity.this);
                Message message = handler.obtainMessage();
                try {
                    HctResult result = controller.getRelevanceHint(machineId);
                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }
                } catch (Exception e) {
                    message.what = HctConstants.STATUS_FAILD;
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();

    }

    /**
     * 隐藏所有特殊机型的组件展示
     */
    private void hideSpecialMachineView() {
        mutipleMachine.hideView();
        jy_HotWaterMachine.hideView();
        sy_HotWaterMachine.hideView();
        bigunit.hideView();
    }

    /**
     * 条码校验 --根据条码前五位显示不同机型的特有属性
     * 机型--1:多联机 2:家用热水机 3：商用热水机 4：大机组0：其它
     */
    private boolean barcodeValidate() {
        builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.dialog_default_title_hint);
        builder.setPositiveButton(R.string.i_konw, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        String barcode = code_edit.getText().toString().replace(" ", "");
        if (!TextUtils.isEmpty(machineName)) {
            //风管机的条码要求：型号是FG开头，且第17位为O需要弹框提示“扫描内机条码”
            if (machineName.length() > 18 && machineName.startsWith("FG")) {
                char indexChar = machineName.charAt(17);
                if (indexChar == 'O') {
                    builder.setMessage(R.string.wrong_barcode_1);
                    builder.create().show();
                    wrongBarcode = true;
                } else {
                    wrongBarcode = false;
                }
            } else if (machineName.startsWith("SX")) {//热水机的条码要求：型号是SX开头则提示“扫描外机条码”
                builder.setMessage(R.string.wrong_barcode_2);
                builder.create().show();
                wrongBarcode = true;
            } else {
                wrongBarcode = false;
            }
        } else {
            wrongBarcode = false;
        }

		/*
         * 2016.5.27--390694添加
		 * 判断条码是否输入非法字符
		 */
        if (StringUtil.isBarcodeLegal(barcode)) {
            Utils.showToastCenter(context,
                    getString(R.string.barcode_info_is_vilidate));
            return false;
        }

        //判断是否有中文
        if (Utils.chineseValid(barcode)) {
            Utils.showToastCenter(context,
                    getString(R.string.barcode_length_is_zh));
            return false;
        }


        barcode = barcode.toUpperCase();//将所有字母转为大写
        code_edit.setText(barcode);


        if (barcode.contains(",")) {

            String[] barcodes = barcode.split(",");
            for (int i = 0; i < barcodes.length; i++) {
                //判断条码长度
                if (!(barcodes[i].length() == 13
                        || barcode.length() == 15 || barcode
                        .length() == 30)) {
                    Utils.showToastCenter(
                            context,
                            getString(R.string.barcode_length_is_wrong) + "第" + (i + 1) + "条条码");
                    return false;
                }
                // 判断所有条码是否同一机型
                if (!barcodes[0].substring(0, 5).equals(
                        barcodes[i].substring(0, 5))) {
                    Toast.makeText(getApplicationContext(),
                            getString(R.string.barcode_input_many),
                            Toast.LENGTH_LONG).show();
                    return false;
                }


                //多联机请单独获取开机密码
                if (isDuoLianJi(barcodes[i])) {
                    Utils.showToastCenter(context,
                            getString(R.string.toast_is_not_fgj));
                    return false;
                }
                // 热水机请单独获取开机密码
                if (isHotWater(barcodes[i]) || isCommercialWaterMachine(barcodes[i])) {
                    Utils.showToastCenter(context,
                            getString(R.string.barcode_info_is_wrong_4));
                    return false;
                }
                // 大机组请单独获取开机密码
                if (isBigUnit(barcodes[i])) {
                    Utils.showToastCenter(context,
                            getString(R.string.barcode_info_is_wrong_3));
                    return false;
                }
            }
            if (checkContainSameBarcode(barcode)) {//多条码时，判断是否存在重复条码
                Toast.makeText(context,
                        getString(R.string.barcode_is_same),
                        Toast.LENGTH_SHORT).show();
                return false;
            }
            //isHaveSameMachineCode(barcode);
        } else {
            //判断条码长度
            if (!(barcode.length() == 13
                    || barcode.length() == 15 || barcode
                    .length() == 30)) {
                Utils.showToastCenter(
                        context,
                        getString(R.string.barcode_length_is_wrong));
                return false;
            }
        }

        if (MachineType != 0 && !isDuoLianJi(barcode) && !isCommercialWaterMachine(barcode) && !isHotWater(barcode) && !isBigUnit(barcode)) {
            MachineType = 0;
            hideSpecialMachineView();
            return false;
        } else if (isDuoLianJi(barcode) && MachineType != 1) {

            MachineType = 1;
            hideSpecialMachineView();
            mutipleMachine.showView();
            return false;
        } else if (isCommercialWaterMachine(barcode) && MachineType != 3) {
            MachineType = 3;
            hideSpecialMachineView();
            sy_HotWaterMachine.showView();
            return false;
        } else if (isHotWater(barcode)) {
            String fiveCode = barcode.substring(0, 5);
            if (!fiveCode.equals(jy_HotWaterMachine.getFiveCode())) {//条码前5位发生变化
                jy_HotWaterMachine.setFiveCode(fiveCode);
                /**
                 * 390694--20160505屏蔽
                 */
                /*jy_HotWaterMachine.initMachineAttr(barcode);//重新根据条码初始化 :热水机配套水箱
                AlertDialog.Builder builder = new Builder(StartPwdActivity.this);//增加弹出提醒，增加时间，以完成配套水箱的更新线程
				builder.setTitle(R.string.dialog_default_title_hint)
						.setMessage(R.string.tip_auxiliary_water_ank)
						.setNegativeButton(
								getString(R.string.dialog_confirm_hint),
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
									}
								}).create().show();*/
            }
            if (MachineType != 2) {
                MachineType = 2;
                hideSpecialMachineView();
                jy_HotWaterMachine.showView();
                return false;
            }
        } else if (isBigUnit(barcode) && MachineType != 4) {
            MachineType = 4;
            hideSpecialMachineView();
            bigunit.showView();
            return false;
        }
        return true;
    }

    /**
     * 校验获取公共组件的值
     *
     * @return
     */
    private PwdEntity getBaseViewValue() {
        //条码校验 --根据条码前五位显示不同机型的特有属性
        // 机型--1:多联机 2:家用热水机 3：商用热水机 4：大机组0：其它
        if (!barcodeValidate()) {
            return null;
        }
        String barcode = code_edit.getText().toString();
        String phone = LoginResultStoreUtil.get(context).phone;// 登录时的电话传过来
        String street = address_edit.getText().toString().replace(" ", "");
        String projectName = project_edit.getText().toString().replace(" ", "");
        String owner = name_edit.getText().toString().replace(" ", "");
        String ownerPhone = phone_edit.getText().toString().replace(" ", "");
        String remark = note_edit.getText().toString().replace(" ", "");
        Spinner industryBtn = (Spinner) findViewById(R.id.btn_industry);
        industryEntity = (IndustryEntity) industryBtn.getTag();
        if (phone.isEmpty() || street.isEmpty() || projectName.isEmpty() || owner.isEmpty() || ownerPhone.isEmpty() || industryEntity.en_name.equals("")) {
            Utils.showToastCenter(context, getString(R.string.barcode_info_is_incomplete));
            return null;
        }
        /*
         * 是否已填写地址
		 */
        if (!locationEntity.isTextLocation()) {
            Toast.makeText(StartPwdActivity.this, R.string.nolocation_hint, Toast.LENGTH_SHORT).show();
            return null;
        }
        /*
         * 是否能定位
		 */
        if (!locationEntity.isLocation()) {
            Toast.makeText(StartPwdActivity.this, R.string.gps_waiting_hint, Toast.LENGTH_SHORT).show();
            return null;
        }
        if (!StringUtil.isNameLegal(owner)) {
            Utils.showToastCenter(context, getString(R.string.barcode_name_is_wrong));
            return null;
        }
        if (owner.replace(" ", "").length() > 20) {
            Utils.showToastCenter(context, getString(R.string.barcode_name_length_is_wrong));
            return null;
        }
        if (projectName.replace(" ", "").length() > 40) {
            Utils.showToastCenter(context, getString(R.string.barcode_project_name_length_is_wrong));
            return null;
        }
        if (!StringUtil.isPhone(ownerPhone)
        /* || !StringUtil.isPhone(linkManPhone) */) {
            Utils.showToastCenter(context, getString(R.string.barcode_phone_is_wrong));
            return null;
        }
        PwdEntity entity = new PwdEntity();
        entity.stripeCode = barcode;
        entity.phone = phone;
        entity.street = street;
        entity.projectName = projectName;
        entity.ownerName = owner;
        entity.ownerPhone = ownerPhone;
        entity.remark = remark;
        entity.industry = industryEntity.en_name;

        entity.province = locationEntity.getProvince();
        entity.city = locationEntity.getCity();
        entity.district = locationEntity.getDistrict();
        return entity;
    }

    /**
     * 点击事件
     */
    private OnClickListener mOnClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_back:
                    KeyboardUtil keyboardUtil = new KeyboardUtil();
                    keyboardUtil.hideSoftKeyboard(v);
                    Intent intent2 = new Intent();
                    intent2.setClass(StartPwdActivity.this, MainActivityV2.class);
                    if (loginBundle != null) {
                        intent2.putExtras(loginBundle);
                        intent2.putExtra("assignLogin", "false");
                    }

                    startActivity(intent2);
                    finish();

                    break;
                case R.id.btn_right:
                    Intent intent = new Intent(context, HisRecordActivity.class);
                    //传递服务器类型判断结果至历史记录界面
                    intent.putExtra("PING_COUNT", pingCount);
                    intent.putExtra("WHICH_SERVER", isCloudServer);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    if (bigUnitPwdStatusMsg != 0) {
                        bigUnitPwdStatusMsg = 0;
                    }
                    getBigUnitNewMessage();
                    break;
                case R.id.btn_right_first:// 帮助
                    intent = new Intent(context, SupportMidActivity.class);
                    intent.putExtra(HctConstants.ON_ACTIVITY_KEY_INFO_TYPE, SupportMidActivity.MACHINE_HELP);
                    startActivity(intent);
                    break;
                case R.id.sub_btn:// 提交
                    PwdEntity entity = getBaseViewValue();//校验组件
                    boolean flag = true;
                    switch (MachineType) {//校验特殊机型对应的组件
                        case 1:
                            flag = mutipleMachine.validateView();
                            break;
                        case 2:
                            flag = jy_HotWaterMachine.validateView();
                            break;
                        case 3:
                            flag = sy_HotWaterMachine.validateView();
                            break;
                        case 4:
                            flag = bigunit.validateView();
                            break;
                    }
                    if (flag && entity != null) {
                        //add 需要在此处增加机型提示 需要在此处第二次操作数据库，因为一次不能保证能查到
                        getMachineIdFromDb(code_edit.getText().toString());
                        if (!TextUtils.isEmpty(machineId)) {
                            if (isCloudServer) {//2017-1-13  390694 如果是在云平台上，不获取关联提示，直接拿密码
                                LogUtil.i("DATA", "在云平台上，不获取关联提示");
                                getBootPwd(entity);
                            } else {
                                //从后台拿关联提示 工作线程中执行
                                if (wrongBarcode) {
                                } else {
                                    //关联提示
                                    showRelevanceHint(machineId, entity);
                                }
                            }
                        } else {
                            //无该机型提示时直接获取开机密码
                            // 获取开机密码
                            getBootPwd(entity);
                        }
                    }
                    break;
                case R.id.scan_btn:// 二维码扫描
                    intent = new Intent(context, CaptureActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivityForResult(intent, ZXING_DATA);
                    break;
                case R.id.pic_btn:// 读取图库二维码
                    // startAlbum();
                    ImageCropUtil util = new ImageCropUtil();
                    util.doCropImage(StartPwdActivity.this, FLAG_MODIFY_FINISH);
                    break;

                default:
                    break;
            }
        }

        @Deprecated
        private void startAlbum() {
            Intent i = new Intent();
            i.setAction(Intent.ACTION_PICK);
            i.setType("image/*");
            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    };


    //先从数据库中获取机型id
    private void getMachineIdFromDb(String barcode) {
        try {
            MachineEntity machineEntity = dbController.getMachineEntity(barcode);
            if (machineEntity != null) {
                machineId = machineEntity.id;
                machineName = machineEntity.name;
            } else {//数据库不存在机型的的条码时不提示
                machineId = "";
                machineName = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否已存在该新增的条码
     *
     * @param barcode
     * @return
     */
    private boolean checkHasSameBarcode(String barcode, String result) {

        if (barcode.contains(",")) {
            String[] codeArr = barcode.split(",");
            for (String code : codeArr) {
                if (code.equals(result)) {
                    return true;
                }
            }
        } else {
            if (barcode.equals(result)) {
                return true;
            }
        }
        return false;

    }

    /**
     * 判断是否包含重复条码
     *
     * @param barcode
     * @return wuhs20151224
     */
    private boolean checkContainSameBarcode(String barcode) {
        String newBarcode = "@," + barcode + ",@";//修饰条码
        if (barcode.contains(",")) {
            String[] codeArr = barcode.split(",");
            for (String code : codeArr) {
                if (!code.equals("@")) {
                    String[] splitBarcod = newBarcode.split(code);//遍历得出每个条码，并用该条码进行分割
                    if (splitBarcod.length > 2) {//如果该条码为唯一，则修饰条码只会被分割为2份
                        return true;
                    }
                }
            }
        }
        return false;

    }

    /**
     * 判断是否包含重复条码
     *
     * @param barcode
     * @return
     */
    private boolean isHaveSameMachineCode(String barcode) {
        if (barcode == null || barcode.replace(" ", "").length() == 0) {
            return false;
        }
        if (!barcode.contains(",")) {
            return false;
        }
        String[] codes = barcode.split(",");
        for (int i = 0; i < codes.length; i++) {
            String code1 = codes[i];
            for (int j = i + 1; j < codes.length; j++) {
                String code2 = codes[j];
                if (code1.equals(code2)) {
                    return true;
                }
            }
        }
        return false;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != context.RESULT_OK)
            return;
        if (requestCode == RESULT_LOAD_IMAGE) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            readerFromSDCardPath(picturePath);
        } else if (requestCode == FLAG_MODIFY_FINISH && resultCode == RESULT_OK) {
            if (data != null) {
                ImageCropUtil cropUtil = new ImageCropUtil();
                readerFromSDCardPath(cropUtil.getTmpFilePath());
            }

        } else if (requestCode == RefrigerantCalculatorActivity.REQUEST_CODE) {//多联机冷媒计算
            if (data != null) {
                String refrigerantCalculator = data.getStringExtra("RefrigerantCalculator");
                ((TextView) findViewById(R.id.edit_lengmei_add)).setText(refrigerantCalculator);
            }
        } else {//扫描条码返回
            String result = data.getStringExtra("result");
            if (result == null) {
                return;
            }
            String codeText = code_edit.getText().toString().replace(" ", "");
            if (!codeText.replace(" ", "").equals("")) {
                if (checkHasSameBarcode(codeText, result)) {
                    Toast.makeText(context,
                            getString(R.string.barcode_info_is_repeat),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            if (code_edit.getText().toString().replace(" ", "").equals("")) {
                code_edit.setText(result);
            } else {
                code_edit.setText(code_edit.getText() + "," + result);
            }
            Utils.setLastSelection(code_edit);
        }
    }

    /**
     * 是否是多联机系列
     */
    private boolean isDuoLianJi(String lBarcode) {
        if (lBarcode == null || lBarcode.length() < 5) {
            return false;
        }
        DbController controller = new DbController(context);
        MachineEntity lEntity = controller.getMachineEntity(lBarcode.substring(
                0, 5));
        if (lEntity == null || lEntity.seriesId.replace(" ", "").length() < 1) {
            return false;
        }
        SerieEntity serieEntity = controller.getSerieEntity(lEntity.seriesId);
        if (serieEntity != null && serieEntity.seriesTypeName != null) {

            return serieEntity.seriesTypeName.equals("mutiple_Machine");
        }
        return false;
    }


    /**
     * 是否是商用热水机大类型
     *
     * @return
     */
    private boolean isCommercialWaterMachine(String lBarcode) {
        if (lBarcode == null || lBarcode.length() < 5) {
            return false;
        }
        DbController controller = new DbController(context);
        MachineEntity lEntity = controller.getMachineEntity(lBarcode.substring(
                0, 5));
        if (lEntity == null || lEntity.seriesId.replace(" ", "").length() < 1) {
            return false;
        }
        SerieEntity serieEntity = controller.getSerieEntity(lEntity.seriesId);
        if (serieEntity != null && serieEntity.seriesTypeName != null) {

            return serieEntity.seriesTypeName.equals("commercialHot_Machine");
        }
        return false;
    }

    /**
     * 是否是家用热水机系列
     */
    private boolean isHotWater(String lBarcode) {
        if (lBarcode == null || lBarcode.length() < 5) {
            return false;
        }
        DbController controller = new DbController(context);
        MachineEntity lEntity = controller.getMachineEntity(lBarcode.substring(
                0, 5));
        if (lEntity == null || lEntity.seriesId.replace(" ", "").length() < 1) {
            return false;
        }
        SerieEntity serieEntity = controller.getSerieEntity(lEntity.seriesId);
        if (serieEntity != null && serieEntity.seriesTypeName != null) {
            return serieEntity.seriesTypeName.equals("hotWater_machine");
        }
        return false;
    }

    /**
     * 是否是大机组
     */
    private boolean isBigUnit(String lBarcode) {
        Log.i("DATA", "isBigUnit----1---" + lBarcode);

        if (lBarcode == null || lBarcode.length() < 5) {
            return false;
        }
        DbController controller = new DbController(context);
        MachineEntity lEntity = controller.getMachineEntity(lBarcode.substring(
                0, 5));
        if (lEntity == null || lEntity.seriesId.replace(" ", "").length() < 1) {
            return false;
        }

        SerieEntity serieEntity = controller.getSerieEntity(lEntity.seriesId);
        Log.i("DATA", "isBigUnit----1---" + serieEntity.seriesTypeName);
        if (serieEntity != null && serieEntity.seriesTypeName != null) {
            Log.i("DATA", "isBigUnit----1---" + lBarcode);
            return serieEntity.seriesTypeName.equals("largeUnit_machine");
        }
        /*
         * if (lBarcode.substring(0, 5).equals("95111")) { return true; }
		 */
        return false;

    }

    private void readerFromSDCardPath(String picturePath) {
        try {
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
                bitmap = null;
            }
            DecodeBitmapUtil decodeBitmapUtil = new DecodeBitmapUtil();
            bitmap = decodeBitmapUtil.getHorizontalBitmap(picturePath);

            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            RGBLuminanceSource source = new RGBLuminanceSource(bitmap);
            BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
            MultiFormatReader reader2 = new MultiFormatReader();
            Result result;
            try {
                result = reader2.decode(bitmap1, hints);
                if (code_edit.getText().toString().replace(" ", "").equals("")) {
                    code_edit.setText(result.getText());
                } else {
                    code_edit.setText(code_edit.getText() + ","
                            + result.getText());
                }
                Utils.setLastSelection(code_edit);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Utils.showToastCenter(context,
                        getString(R.string.not_found_the_barcode_hint));
            }
        } catch (Exception e) {
        }
    }

    /**
     * 省份
     */
    public void initSpinner1() {
        p_list.clear();
        p_list.add(BaseListItemEntity.getInitName());
        try {
            String sql = "select * from province";
            Cursor cursor = locationdb.rawQuery(sql, null);

            while (cursor.moveToNext()) {
                BaseListItemEntity myListItem = new BaseListItemEntity();
                String code = cursor.getString(cursor.getColumnIndex("code"));
//				byte bytes[] = cursor.getBlob(2);
//				String name = new String(bytes, "UTF-8");
                String name = cursor.getString(cursor.getColumnIndex("name"));
                myListItem.setName(name.trim());
                myListItem.setPcode(code);
                p_list.add(myListItem);
            }
            cursor.close();

        } catch (Exception e) {

        }
//		dbm.closeDatabase();
//		db.close();

        BaseSpinnerAdapter myAdapter = new BaseSpinnerAdapter(this, p_list);
        province_spinner.setAdapter(myAdapter);
        province_spinner.setOnItemSelectedListener(new SpinnerOnSelectedListener1());
    }

    /**
     * 城市
     *
     * @param pcode
     */
    public void initSpinner2(String pcode) {
        List<BaseListItemEntity> c_list = new ArrayList<BaseListItemEntity>();
        c_list.add(BaseListItemEntity.getInitName());
        try {
            String sql = "select * from city where pcode='" + pcode + "'";
            Cursor cursor = locationdb.rawQuery(sql, null);
            while (cursor.moveToNext()) {
                BaseListItemEntity myListItem = new BaseListItemEntity();
                String code = cursor.getString(cursor.getColumnIndex("code"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                myListItem.setName(name.trim());
                myListItem.setPcode(code);
                c_list.add(myListItem);
            }
            cursor.close();
        } catch (Exception e) {
        }

        BaseSpinnerAdapter myAdapter = new BaseSpinnerAdapter(this, c_list);
        city_spinner.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();
        city_spinner.setOnItemSelectedListener(new SpinnerOnSelectedListener2());
        if (locationEntity.getCity_loc() != null) {
            for (int i = 0; i < c_list.size(); i++) {
                if (c_list.get(i).getName().equals(locationEntity.getCity_loc())) {
                    city_spinner.setSelection(i, true);
                    break;
                }
            }
        }
    }

    /**
     * 区
     *
     * @param pcode
     */
    public void initSpinner3(String pcode) {
        List<BaseListItemEntity> d_list = new ArrayList<BaseListItemEntity>();

        d_list.add(BaseListItemEntity.getInitName());
        try {
            String sql = "select * from district where pcode='" + pcode + "'";
            Cursor cursor = locationdb.rawQuery(sql, null);

            while (cursor.moveToNext()) {
                BaseListItemEntity myListItem = new BaseListItemEntity();
                String code = cursor.getString(cursor.getColumnIndex("code"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                myListItem.setName(name.trim());
                myListItem.setPcode(code);
                d_list.add(myListItem);
            }
            cursor.close();

        } catch (Exception e) {
        }

        //如果该城市下没有区/镇，则置灰
        if (d_list.size() < 2) {
            d_list = new ArrayList<BaseListItemEntity>();
            BaseListItemEntity myListItem = new BaseListItemEntity();
            myListItem.setName("");
            myListItem.setPcode("");
            d_list.add(myListItem);
        }

        BaseSpinnerAdapter myAdapter = new BaseSpinnerAdapter(this, d_list);
        district_spinner.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();

        district_spinner.setOnItemSelectedListener(new SpinnerOnSelectedListener3());
        if (locationEntity.getDistrict_loc() != null) {
            for (int i = 0; i < d_list.size(); i++) {
                if (d_list.get(i).getName().equals(locationEntity.getDistrict_loc())) {
                    district_spinner.setSelection(i, true);
                    break;
                }
            }
        }
    }

    /**
     * @author 390694 城市下拉框监听事件，获取省市provice
     */
    class SpinnerOnSelectedListener1 implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            String province = ((BaseListItemEntity) adapterView.getItemAtPosition(position)).getName();
            locationEntity.setProvince(province);
            String pcode = ((BaseListItemEntity) adapterView.getItemAtPosition(position)).getPcode();
            initSpinner2(pcode);
            // initSpinner3(pcode);
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
            // TODO Auto-generated method stub
        }
    }

    class SpinnerOnSelectedListener2 implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            String city = ((BaseListItemEntity) adapterView.getItemAtPosition(position)).getName();
            locationEntity.setCity(city);
            String pcode = ((BaseListItemEntity) adapterView.getItemAtPosition(position)).getPcode();
            initSpinner3(pcode);
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
            // TODO Auto-generated method stub
        }
    }

    class SpinnerOnSelectedListener3 implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            String district = ((BaseListItemEntity) adapterView.getItemAtPosition(position)).getName();
            locationEntity.setDistrict(district);
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationServiceUtil.stopLocationService();
        mgr.closeDB();
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (bigUnitPwdStatusMsg != 0) {
            bigUnitPwdStatusMsg = 0;
            getBigUnitNewMessage();
        }
        locationServiceUtil.stopLocationService();
        //销毁条码弹框
        if (builder != null) {
            builder.create().dismiss();
            builder = null;
        }
        new MyCustomDialog().destroyDialog();

    }


    /**
     * 显示大机组开机密码状态改变通知
     *
     * @param
     */
    public void getBigUnitNewMessage() {
        if (bigUnitPwdStatusMsg > 0) {
            lyt_msg.setVisibility(View.VISIBLE);
            text_newMessage.setText(Integer.toString(bigUnitPwdStatusMsg));
        } else if (bigUnitPwdStatusMsg <= 0) {
            lyt_msg.setVisibility(View.GONE);
        }
    }

    /**
     * 访问获取大机组的审核状态及正常密码的接口，并将获取到的数据存入数据库
     *
     * @param phone
     * @param personId
     */
    public void getBigUnitExamineStatus(final String phone,
                                        final String personId, final boolean isCloundServer) {

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                HctResult result = new HctResult();
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        result = (HctResult) msg.obj;
                        ArrayList<BigUnitPasswordStatusEntity> dataList = (ArrayList<BigUnitPasswordStatusEntity>) result.data;
                        PwdEntity pwd = null;
                        int newMsg = 0;
                        for (int i = 0; i < dataList.size(); i++) {
                            pwd = new PwdEntity();
                            if (dataList.get(i).verifyStatus.equals("1")) {// 1---审核通过
                                String bootPwdStr = dataList.get(i).bootPwd
                                        .replace("[", "").replace("]", "")
                                        .replace("\"", "");
                                pwd.stripeCode = dataList.get(i).barcode;
                                pwd.openPassword = bootPwdStr;
                                pwd.identityCode = dataList.get(i).identityCode;
                                pwd.verifyStatus = dataList.get(i).verifyStatus;
                                pwd.dateTime = Utils.getNowTime();

                            } else if (dataList.get(i).verifyStatus.equals("2")// 2---审核未通过
                                    || dataList.get(i).examineStatus.equals("2")) {
                                pwd.stripeCode = dataList.get(i).barcode;
                                pwd.refuseReason = dataList.get(i).refuseReason;
                                pwd.openPassword = getResources().getString(
                                        R.string.bigunit_password_apply_result);
                                pwd.identityCode = dataList.get(i).identityCode;
                                pwd.verifyStatus = "2";
                                pwd.dateTime = Utils.getNowTime();

                            }
                            int num = mgr.updateBigUnitPwd(pwd);
                            newMsg = newMsg + num;
                        }

                        bigUnitPwdStatusMsg = newMsg;

                        // Log.i("DATA", "大机组数据更新数-1=" + bigUnitPwdStatusMsg);
                        // 大机组开机密码状态通知
                        getBigUnitNewMessage();
                        break;

                    case HctConstants.STATUS_FAILD:

                        break;
                }
            }
        };
        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(context);
                    HctResult result = new HctResult();
                    result = controller.getStatusForBigUnitPwd(phone, personId, isCloundServer);
                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }
                } catch (Exception e) {
                    message.what = HctConstants.STATUS_FAILD;
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }

        }.start();
    }

    private void setListener() {
        cb_batchInstallation.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    myEditor.putBoolean(HctConstants.KEY_VALUE_BATCH_INSTALLATION,
                            true);
                } else {
                    myEditor.putBoolean(HctConstants.KEY_VALUE_BATCH_INSTALLATION,
                            false);
                }
                myEditor.commit();

            }
        });
    }

}
